import functools
import datetime
import random
import qiniu
from flask import current_app, app
from flask import g
from flask import session


def do_index_class(value):
    """自定义过滤器，过滤点击排序html的class"""
    if value == 1:
        return "first"  # 只能return
    elif value == 2:
        return "second"
    elif value == 3:
        return "third"
    else:
        return ""


def user_login_data(view_func):
    """查询当前客户端登陆用户信息的装饰其"""
    @functools.wraps(view_func)
    def wrapper(*args, **kwargs):
        user_id = session.get("user_id")
        from info.models import User
        user = None
        if user_id:
            # 根据user_id到数据库中查询用户信息
            try:
                user = User.query.get(user_id)
            except Exception as e:
                current_app.logger.error(e)

        # 通过g变量，保存用户信息，后面提供给视图使用，视图中可以通过　g.user　来获取数据
        g.user = user

        return view_func(*args, **kwargs)

    return wrapper


def file_storage(data):
    """
    :param data: 上传到七牛云上面的文件数据
    :return:
    """
    access_key = "Bvcn0TrhjtftbW9NqBMFloPCpCYzzz3SN2nDhHeM"
    secret_key = "isrFwzI1DOqpQ3FOtGr3By3xcUUbXZGFAyMUFT22"
    bucket_name = "python-flask01"

    # 上面的信息，需要手动加到配置中。

    q = qiniu.Auth(access_key, secret_key)  # 七牛云操作对象
    token = q.upload_token(bucket_name)  # bucket_name 存储空间名  python-flask01
    ret, info = qiniu.put_data(token, None, data)
    print(ret)
    return ret.get("key")
